//全局axios实例，发送请求都是使用这个axios实例
import axios from 'axios'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from './stores/useLoginUserstore'
import ACCESS_ENUM from './access/accessEnum'

// 创建 Axios 实例
const myAxios = axios.create({
  baseURL: 'http://localhost:8101',
  timeout: 1200000,
  //携带cookie
  withCredentials: true,
})

// 全局请求拦截器
myAxios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  },
)

// 全局响应拦截器
myAxios.interceptors.response.use(
  function (response) {
    //对响应进行结构
    const { data } = response
    // 未登录
    if (data.code === 40100) {
      // 获取当前用户信息
      const userStore = useLoginUserStore()
      const userRole = userStore.loginUser.userRole
      
      // 不是获取用户信息的请求，并且用户目前不是已经在登录页面或注册页面，则跳转到对应角色的登录页面
      if (!response.request.responseURL.includes('/user/get/login') && 
          !window.location.pathname.includes('/user/login') && 
          !window.location.pathname.includes('/admin/login') && 
          !window.location.pathname.includes('/recruiter/login') && 
          !window.location.pathname.includes('/recruiter/register')) {
        
        message.warning('请先登录')
        
        // 根据用户角色跳转到对应的登录页面
        if (userRole === ACCESS_ENUM.ADMIN || window.location.pathname.includes('/admin')) {
          window.location.href = `/admin/login?redirect=${window.location.href}`
        } else if (userRole === ACCESS_ENUM.RECRUITER || window.location.pathname.includes('/recruiter')) {
          window.location.href = `/recruiter/login?redirect=${window.location.href}`
        } else {
          window.location.href = `/user/login?redirect=${window.location.href}`
        }
        return Promise.reject(data)
      }
    }
    return data
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    message.error("故障原因："+error)
    return Promise.reject(error)
  },
)

export default myAxios
